﻿using System;
using RpcHelper;
using RpcHelper.Config;
using RpcModular;
using RpcModular.Model;
using Wedonek.RpcStore.Gateway.Interface;
using Wedonek.RpcStore.Gateway.Model;
using Wedonek.RpcStore.Service.Interface;
using Wedonek.RpcStore.Service.Model;

namespace Wedonek.RpcStore.Gateway.Service
{
    internal class AdminService : IAdminService
    {
        private readonly ISysConfigCollect _Config = null;
        private readonly IAccreditService _Accredit = null;
        public AdminService(ISysConfigCollect config, IAccreditService accredit)
        {
            this._Accredit = accredit;
            this._Config = config;
        }
        public void SetAdminPwd(IUserState state, string pwd)
        {
            string key = string.Concat("RpcAdmin_", state["LoginName"]);
            SysConfigDatum config = this._Config.Find(RpcClient.RpcClient.CurrentSource.SystemType, key);
            pwd = string.Concat(pwd, "_6xy3#7a%adxyz").GetMd5().ToLower();
            if (pwd == config.Value)
            {
                return;
            }
            this._Config.Set(config.Id, new SysConfigSetParam
            {
                Value = pwd,
                ValueType = SysConfigValueType.字符串,
                IsEnable = true,
                Prower = config.Prower,
                ToUpdateTime = DateTime.Now
            });
            LocalConfig.Local.SetConfig(key, pwd, 15);
        }
        public Guid AdminLogin(AdminLogin login)
        {
            string key = string.Concat("RpcAdmin_", login.LoginName);
            string pwd = RpcClient.RpcClient.Config.GetConfigVal(key);
            if (pwd.IsNull())
            {
                throw new ErrorException("rpc.admin.pwd.error");
            }
            else  if (pwd != string.Concat(login.Pwd, "_6xy3#7a%adxyz").GetMd5().ToLower())
            {
                throw new ErrorException("rpc.admin.pwd.error");
            }
            UserState state = new UserState();
            state["LoginName"] = login.LoginName;
            this._Accredit.AddAccredit(key, null, state);
            return state.AccreditId;
        }

        public void RegAdmin(AdminLogin reg, string clientIp)
        {
            string limitIp = RpcClient.RpcClient.Config.GetConfigVal("limitIp", "127.0.0.1");
            if (limitIp != clientIp)
            {
                throw new ErrorException("rpc.no.prower");
            }
            string key = string.Concat("RpcAdmin_", reg.LoginName);
            string pwd = string.Concat(reg.Pwd, "_6xy3#7a%adxyz").GetMd5().ToLower();
            this._Config.Add(new SysConfigAddParam
            {
                Name = key,
                RpcMerId = 0,
                IsEnable=true,
                SystemType = RpcClient.RpcClient.CurrentSource.SystemType,
                ValueType = SysConfigValueType.字符串,
                Value = pwd
            });
            LocalConfig.Local.SetConfig(key, pwd, 15);
        }
    }
}
